#!/usr/bin/env python
#yatii - Yet Another TeX Image Interface
#Copyright (C) 2007  K Hartvig Jensen (kare1234@gmail.com)
#                http://www.hartvig.de

#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#####
# Definitions, import channel list from file
#####
from Tkinter import *
import os
import Image
import ImageTk
import Tkinter
import sys

# Check if the right input arguments have been passed.
try:    
    test1=sys.argv[1]
    test2=sys.argv[2]
except:
    print 'Usage:\nyatii.py configfilename imagefilename'
    quit()

########
# Init function
########
class App:
    
    def __init__(self, master):
	# initialise frame        
        frame = Frame(master)
        frame.grid()
        self.frame=frame

        # Get input arguments
        self.imagefilename=sys.argv[2]
        self.configfilename=sys.argv[1]
        print '1'
	# load config file
        self.loadconfigfile()
        print '2'
    # generate thumbnail    
        #self.latex()
        #self.updateimage()
        print '3'
	# populate gui with text stings from config file
        self.generateTextLabels()    
 

	#channel selector label
        self.chanselectlabel = Label(frame,text='Text:')
        self.chanselectlabel.grid(row=4, column=0)
        self.chanselectlabel = Label(frame,text='x position:')
        self.chanselectlabel.grid(row=4, column=1)
        self.chanselectlabel = Label(frame,text='y position:')
        self.chanselectlabel.grid(row=4, column=2)
        
	# increment selector radiobuttons
        self.dx = DoubleVar()
        self.dxradiobutton1 = Radiobutton(frame,fg="black", text="dx=1", variable=self.dx,value=1)
        self.dxradiobutton1.grid(row=5,column=3)
        self.dxradiobutton1 = Radiobutton(frame,fg="black", text="dx=0.1", variable=self.dx,value=0.1)
        self.dxradiobutton1.grid(row=5,column=4)
        self.dxradiobutton1.select()
        self.dxradiobutton1 = Radiobutton(frame,fg="black", text="dx=0.01", variable=self.dx,value=0.01)
        self.dxradiobutton1.grid(row=5,column=5)
        self.dxradiobutton1 = Radiobutton(frame,fg="black", text="dx=0.001", variable=self.dx,value=0.001)
        self.dxradiobutton1.grid(row=6,column=5)
        
	# Add new text string to image entry form
        self.buttonWidth=18
        self.newTextString=StringVar()
    	addNewTextStringEntry=Tkinter.Entry(frame, width=30,textvariable=self.newTextString)
    	addNewTextStringEntry.grid(row=2,column=2)
    	self.addNewTextStringButton = Button(frame, text='Add text',width=self.buttonWidth,command=(lambda: self.addNewText()))
        self.addNewTextStringButton.grid(row=2,column=3)
	# Delete selected string
        self.deleteSelectedStringButton = Button(frame, text='Delete selected string',width=self.buttonWidth,command=(lambda: self.deleteSelectedString()))
        self.deleteSelectedStringButton.grid(row=3,column=3)


        # figure width label
        self.figurewidth = IntVar()
        self.figurewidth.set(12)
        self.figurewidthlabel= Label(frame,textvariable=self.figurewidth)
        self.figurewidthlabel.grid(row=0,column=2) 
        self.figurewidthminusbutton = Button(frame, text='Figure width - 1cm',width=self.buttonWidth,command=(lambda: self.figurewidth.set(self.figurewidth.get()-1)))
        self.figurewidthminusbutton.grid(row=0,column=3)
        self.figurewidthplusbutton = Button(frame, text='Figure width + 1cm',width=self.buttonWidth,command=(lambda: self.figurewidth.set(self.figurewidth.get()+1)))
        self.figurewidthplusbutton.grid(row=0,column=4)
        
	# font size label
        self.fontsize = IntVar()
        self.fontsize.set(12)
        self.fontsizelabel= Label(frame,textvariable=self.fontsize)
        self.fontsizelabel.grid(row=1,column=2) 
        self.fontsizeminusbutton = Button(frame, text='Font size - 1pt',width=self.buttonWidth,command=(lambda: self.fontsize.set(self.fontsize.get()-1)))
        self.fontsizeminusbutton.grid(row=1,column=3)
        self.fontsizeplusbutton = Button(frame, text='Font size + 1pt',width=self.buttonWidth,command=(lambda: self.fontsize.set(self.fontsize.get()+1)))
        self.fontsizeplusbutton.grid(row=1,column=4)
	# create buttons

        self.button = Button(frame, text="QUIT", bg="red",fg="white",width=self.buttonWidth, command=(lambda: self.exit()))
        self.button.grid(row=0,column=0)
        self.button = Button(frame, text="Launch gv", bg="blue",fg="white",width=self.buttonWidth, command=(lambda: self.gv()))
        self.button.grid(row=1,column=0)
	
        self.xpradiobutton = Button(frame, text='LEFT',width=self.buttonWidth,command=(lambda: self.xpos[self.channelid.get()].set(self.xpos[self.channelid.get()].get()-self.dx.get())))
        self.xpradiobutton.grid(row=7,column=3) 
        self.xmradiobutton = Button(frame, text='RIGHT',width=self.buttonWidth,command=(lambda: self.xpos[self.channelid.get()].set(self.xpos[self.channelid.get()].get()+self.dx.get())))
        self.xmradiobutton.grid(row=7,column=5) 
        self.ypradiobutton = Button(frame, text='UP',width=self.buttonWidth,command=(lambda: self.ypos[self.channelid.get()].set(self.ypos[self.channelid.get()].get()+self.dx.get())))
        self.ypradiobutton.grid(row=6,column=4) 
        self.ymradiobutton = Button(frame, text='DOWN',width=self.buttonWidth,command=(lambda: self.ypos[self.channelid.get()].set(self.ypos[self.channelid.get()].get()-self.dx.get())))
        self.ymradiobutton.grid(row=8,column=4)
        
	self.button = Button(frame, text="LaTeX",width=self.buttonWidth, bg="black",fg="white", command=(lambda: self.stopall(self.text,self.xpos,self.ypos)))
        self.button.grid(row=7,column=4)
##############################################################################################################
##### Functions ##############################################################################################
##############################################################################################################
    def loadconfigfile(self):
        f = open(self.configfilename,"rd")
        # chandata[i][0] - text string, eg $\lambda^2$ 
        # chandata[i][1] - text string x-position x, 0<x<1
        # chandata[i][2] - text string y-position y, 0<y<1
        self.chandata=[]
        f = [line[:-1] for line in f]
        for line in f:
            row = []        
            fields = line.split("\t")
            for i in range(3):
                row.append(fields[i])
            self.chandata.append(row)
        #total number of channels
        self.numchan=len(self.chandata)
        self.maxnum=self.numchan
    
    def addNewText(self):
	row=[str(self.newTextString.get()),'0.5','0.5']
	self.chandata.append(row)
  	#total number of channels
        self.numchan=len(self.chandata)
        self.maxnum=self.numchan
	self.generateTextLabels()   

    def deleteSelectedString(self):
	del self.chandata[self.channelid.get()]
	#total number of channels
        self.numchan=len(self.chandata)
        self.maxnum=self.numchan
	self.generateTextLabels()   




    def generateTextLabels(self):
	# print x and y positions
        self.xpos=[]
        self.ypos=[]
        self.text=[]
        for i in range(self.numchan):
            sv1=DoubleVar()
            sv2=DoubleVar()
            sv3=StringVar()
            sv1.set(float(self.chandata[i][1]))
            sv2.set(float(self.chandata[i][2]))
            sv3.set(self.chandata[i][0])
            self.xpos.append(sv1)
            self.ypos.append(sv2)   
            self.text.append(sv3) 
            # make button
            self.xposlabel = Label(self.frame,textvariable=self.xpos[i])
            self.xposlabel.grid(row=5+i, column=1)
            self.xposlabel = Label(self.frame,textvariable=self.ypos[i])
            self.xposlabel.grid(row=5+i, column=2)

	# Last, empty label
	Label(self.frame,text='               ').grid(row=5+self.numchan,column=0)
	Label(self.frame,text='               ').grid(row=5+self.numchan,column=1)
	Label(self.frame,text='               ').grid(row=5+self.numchan,column=2)
		
	#Print types
        self.channelid = IntVar()
        for i in range(self.numchan):
            self.chanselectlabel = Radiobutton(self.frame,text=self.chandata[i][0],variable=self.channelid,value=i)
            self.chanselectlabel.grid(row=5+i, column=0)
        

   # STOP ALL MEDIA PLAYERS     
    def stopall(self,text,xpos,ypos):
        self.preamble()
        self.puttext(text,xpos,ypos)
        self.postamble()
        self.latex()

    # LaTeX Functions
    def latex(self):
        os.popen('latex main.tex ; dvips main.dvi -E -o')
        os.popen('convert main.ps main.gif')
	#root.update()

	# load image
        self.photo1 = PhotoImage(file="main.gif")
        self.updateimage()

    def updateimage(self):
	#create and show image label
        imagelabel = Label(root,image=self.photo1)
        imagelabel.grid(row=3,column=0)
        root.update_idletasks()

    def dvips(self):
        os.popen('latex main.tex ; dvips main.dvi -E -o')
    
    def gv(self):
        os.popen('gv main.ps &')

    def preamble(self):
        os.popen('rm main.tex')
        os.popen("echo '\documentclass["+str(self.fontsize.get())+"pt]{article}' > main.tex")
        os.popen("echo '\usepackage[dvips]{graphicx,color}' >> main.tex")
        os.popen("echo '\usepackage{textcomp}' >> main.tex")
        os.popen("echo '\usepackage{rotating}' >> main.tex")
        os.popen("echo '\setlength{\unitlength}{"+str(self.figurewidth.get())+"cm}' >> main.tex")
        os.popen("echo '\pagestyle{empty}' >> main.tex")
        os.popen(r'""echo \\\\begin{document} >> main.tex""')
        os.popen(r'""echo \\\\begin{picture}\(1,1\) >> main.tex""')
        os.popen("echo '\put(0.0,0.0){\includegraphics[width="+str(self.figurewidth.get())+"cm]{"+self.imagefilename+"}}' >> main.tex")
    
    def puttext(self,text,xpos,ypos):
        os.popen('rm config.txt')   
        for i in range(self.numchan):
            # write to tex file
            os.popen("echo '\put("+str(self.xpos[i].get())+","+str(self.ypos[i].get())+"){"+self.text[i].get()+"}' >> main.tex")
            # update channellist.txt
            os.popen("echo '"+self.text[i].get()+"\t"+str(self.xpos[i].get())+"\t"+str(self.ypos[i].get())+"' >> config.txt")
            
    def postamble(self):
        os.popen("echo '\end{picture}' >> main.tex")
        os.popen("echo '\end{document}' >> main.tex")
    # QUIT FUNCTION 
    def exit(self):
        root.quit()
##############################################################################################################
#####           ##############################################################################################
##############################################################################################################  

    
root = Tk()
#root.geometry("640x100")
root.title('yaTii')
app = App(root)
root.mainloop()
# load image
photo1 = PhotoImage(file="main.gif")

#create and show image label
label = Label(root,image=photo1)
label.grid(row=2,column=0)


